let app = getApp()
let config = require('../config.js')
/*
显示弹窗提示
url:        请求接口
parms:      请求参数
successCb:  成功回调
errorCb:    失败回调,
session:    头部数据方式
 */

function ajaxPromiseReq(options, successCb, errorCb) {
    var paramSession = ['application/json', 'application/x-www-form-urlencoded']
    var params = {};
    for (var i in options.params) {
        if (typeof(options.params[i]) == 'undefined') {
            params[i] = ''
        } else {
            params[i] = options.params[i]
        }
    }
    wx.request({
        url: config.interfaceHost + options.url,
        data: params,
        dataType: "json",
        method: "POST",
        header: {
            'content-type': options.session ? paramSession[options.session] : paramSession[0],
            'site': config.site,
            'os': config.os,
            'token': wx.getStorageSync('token')
        },
        success: function(res) {
            if (res.data.code == '1') {
                successCb(res.data);
            } else if (res.data.code=='2'){
               
                wx.showModal({
                    title: '温馨提示',
                    content: res.data.msg,
                })
                // setTimeout(function(){
                //     successCb(res.data);
                // },1000)
                
            }
            else {
                if(res.data.code=='-99'){
                    if (!wx.getStorageSync('is_author')) {
                        wx.navigateTo({
                            url: '/pages/author_login/author_login',
                        })
                        wx.setStorageSync('is_author', true)

                    }
                    
                } else if (res.data.code == '-90'){
                    wx.navigateTo({
                        url: '/pages/bind_phone/bind_phone',
                    })
                }else{
                    setTimeout(function () {
                        wx.showToast({
                            icon: "none",
                            title: res.data.msg,
                        })
                    })
                }
                
                return;
            }

        },
        fail: function(res) {
            console.log(res)
            errorCb(res.data)
        }
    })

}
const request = function(params) {
    return new Promise(function(resolve, reject) {
        ajaxPromiseReq(params, function(data) {
            resolve(data);
        }, function(data) {
            reject(data)
        })
    })
}
module.exports = {
    request: request
}